﻿@inject IJSRuntime JS

<div class="page-button-card">
    <CnGalWebSite.Components.Buttons.MasaButton Fab XSmall Icon="@IconType.Left.ToIconString()" OnClick="Previous" />
    <div class="page-count primary-text title-large">
        @pageString
    </div>
    <CnGalWebSite.Components.Buttons.MasaButton Fab XSmall Icon="@IconType.Right.ToIconString()" OnClick="Next" />
</div>

@code {
    [Parameter]
    [EditorRequired]
    public string LayoutId{ get; set; }

    int totalPage;
    int currentPage;
    double pageWidth;
    string pageString;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            await GetPageInfo();
            await Task.Delay(500);
            await GetPageInfo();
        }
    }


    public async Task GetPageInfo()
    {
        var left = await JS.InvokeAsync<double>("getElementScrollLeft", LayoutId);
        var totalWidth = await JS.InvokeAsync<double>("getElementScrollWidth", LayoutId);
        var screenWidth = await JS.InvokeAsync<double>("getBodyClientWidth");

        pageWidth = (int)(screenWidth / 2);
        totalPage = (int)Math.Ceiling(totalWidth / pageWidth);
        currentPage = (int)Math.Round(left / pageWidth) + 1;

        pageString = $"{currentPage} / {totalPage-1}";
        StateHasChanged();
    }

    public async Task Next()
    {
        if (currentPage < totalPage)
        {
            await JS.InvokeVoidAsync("setElementScrollLeft", LayoutId, (currentPage + 1) * pageWidth);
            await Task.Delay(500);
        }
        await GetPageInfo();
        StateHasChanged();
    }

    public async Task Previous()
    {
        if (currentPage != 1)
        {

            await JS.InvokeVoidAsync("setElementScrollLeft", LayoutId, (currentPage - 3) * pageWidth);
            await Task.Delay(500);
        }
        await GetPageInfo();
    }

}
